from functools import wraps
from typing import List, Optional, Callable, Any

from flask import request
from common.ApiResponse import ApiResponse
from common.BaseResponse import BaseResponse
from common.ErrorCode import ErrorCode
from utils.ThreadLocal import ThreadLocalUtil
from models import db, User


# 假设我们有一个全局变量或方法来获取当前用户
# 这里是通过id的方式获取用户
def get_current_user():
    user_map = ThreadLocalUtil.get()
    id = user_map.get('id')
    # todo 怎么获取id更好？
    if not id:
        id = request.json.get('id')
    user = db.session.query(User).filter_by(id=id).first()
    print(user)
    return user


def auth_check(required_roles: List[str], error_code: Optional[ErrorCode] = None):
    def decorator(func: Callable) -> Callable:
        @wraps(func)
        def wrapper(*args: Any, **kwargs: Any) -> Any:
            current_user = get_current_user()
            ## 用户不存在或者用户存在但是权限不足
            if not current_user or not any(role == current_user.user_role for role in required_roles):
                error_response = BaseResponse.from_error_code(
                    error_code or ErrorCode.NO_AUTH_ERROR
                )
                return ApiResponse.error(
                    code=error_response.code,
                    message=error_response.message
                )
            return func(*args, **kwargs)
        return wrapper
    return decorator
